package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
	"testGin/entity"
	"testGin/tool"
)

func Login(c *gin.Context) {
	data, _ := c.GetRawData()
	var loginUser entity.User
	_ = json.Unmarshal(data, &loginUser)
	GetDB().Where("username = ? AND password = ?", loginUser.Username, loginUser.Password).First(&loginUser)
	// 默认Id是0，如是非0，则说明数据插入成功
	if loginUser.Id != 0 {
		token := tool.GetToken(loginUser.Id, loginUser.Username)
		srr := strings.Split(loginUser.Type, ",")
		var arr []int
		if len(loginUser.Type) != 0 {
			for i := 0; i < len(srr); i++ {
				num, _ := strconv.Atoi(srr[i])
				arr = append(arr, num)
			}
		}
		loginUser.TypeList = arr
		c.JSON(http.StatusOK, gin.H{
			"msg":   "登录成功",
			"code":  200,
			"data":  loginUser,
			"token": token,
		})
	} else {
		c.JSON(http.StatusBadRequest, tool.R{
			0, "用户名或者密码错误", nil,
		})
	}
}
